package summerprojectFX.parser;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import summerprojectFX.model.Song;


public class TextFile extends FileInputOutput {

	public TextFile(File file){
		super(file);
	}
	
	public Song read(){
		Song newSong = new Song();
		try{
		FileInputStream fis = new FileInputStream(file);
		DataInputStream in = new DataInputStream(fis);
	    BufferedReader br = new BufferedReader(new InputStreamReader(in));
		
		
		try{
		String lyrics = "";
		String title = "";
		while((title = br.readLine()) != null){
			if(title.isEmpty() == false){
				newSong.setTitle(title);
				break;
			}
		}
		
		
		
		
		String temp = "";
		while((temp = br.readLine()) != null){
			lyrics = lyrics + temp + "\n"; 
		}
		newSong.setLyrics(lyrics);
		}catch(Exception e){}
		
		}catch(FileNotFoundException fnfe){
			
		}
		return newSong;
	}

	public void write(Song song, String fileName) {
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(fileName));
                                                      
			try{
				String[] temp = song.getTitle().split("\\(");
				writer.write(temp[0]);
			
			}catch(Exception e){
				writer.write(song.getTitle());
			}
			
			writer.newLine();
			String[] temp1 = song.getLyrics().split("\n");
			for(int i = 0; i < temp1.length; i++){
				writer.write(temp1[i]);
				writer.newLine();
			}

		} catch (IOException e) {
		} finally {
			try {
				if (writer != null)
					writer.close();
			} catch (IOException e) {
			}
		}
		
	}
}
